﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using RiskMan.Config;
using RiskMan.DataClass;
using RiskMan.DataClass.Gerchik;
using RiskMan.Views.Dialogs;

namespace RiskMan.Views.Robot
{
    /// <summary>
    /// Interaction logic for RobotView.xaml
    /// </summary>
    public partial class RobotView
    {
        private DispatcherTimer _dsTimer = new DispatcherTimer();
        private Data DataProvider = MainWindow.StaticLevel._dataProvider;
   
        public RobotView()
        {
            InitializeComponent();
            dtgdRobotGerchik.ItemsSource = MainWindow.StaticLevel._dataProvider.GechikRobotItemList;

        }



        private void Button_AddRow_Click(object sender, RoutedEventArgs e)
        {
            GechikRobotItem item = new GechikRobotItem();
            AddNewGerchikRobot ngr = new AddNewGerchikRobot(item, DataProvider, false);
            ngr.ShowDialog();

            if (item.ClientCode != null)
            {
                if (item.TradeList == null)
                    item.TradeList = new ObservableCollection<TradesOpen>();
                DataProvider.GechikRobotItemList.Add(item);
            }
        }


        private void btnClearData_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < DataProvider.GechikRobotItemList.Count; i++)
            {
                if (DataProvider.GechikRobotItemList[i].Check)
                {
                    DataProvider.GechikRobotItemList[i].TradeList.Clear();
                    DataProvider.GechikRobotItemList[i].CurrentAttempt = 0;
                    DataProvider.GechikRobotItemList[i].BreakevenFlag = false;
                }
            }
        }

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < DataProvider.GechikRobotItemList.Count; i++)
            {
                DataProvider.GechikRobotItemList[i].Check = (sender as CheckBox).IsChecked.Value;
            }
            dtgdRobotGerchik.ItemsSource = DataProvider.GechikRobotItemList;
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {

        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {

        }

        /// <summary>
        /// Удаление всех выделенных роботов.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            for (int j = 0; j < DataProvider.GechikRobotItemList.Count; j++)
            {
                if (DataProvider.GechikRobotItemList[j].Check == true)
                {
                    DataProvider.GechikRobotItemList.RemoveAt(j);
                    j--;
                }
            }
        }

        private void btnCopy_Click(object sender, RoutedEventArgs e)
        {
            if (dtgdRobotGerchik.SelectedItems.Count == 1)
            {
                int index = dtgdRobotGerchik.SelectedIndex + 1;
                dtgdRobotGerchik.UnselectAll();
                try
                {
                    if (new DialogOkCancel("Вы действительно хотите скопировать строку " + index + "?", "Внимание").Result == MessageBoxResult.OK)
                    {
                        var tmp = (GechikRobotItem)Cfg.DeepClone(DataProvider.GechikRobotItemList[index - 1 < 0 ? 0 : index - 1]);
                        if (tmp.IsRun == false)
                            DataProvider.GechikRobotItemList.Add(tmp);
                        else
                            new DialogOkCancel("Для продолжения копирования нужно остановить копируемю строку", "Ошибка");
                    }
                }
                catch
                { }
            }
        }

        private void dtgdRobotGerchik_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            for (int i = 0; i < DataProvider.GechikRobotItemList.Count; i++)
            {
                if (((DataGrid)sender).SelectedIndex == i)
                    dtgdOrder.ItemsSource = DataProvider.GechikRobotItemList[i].TradeList;
            }
        }

        private void dtgdRobotGerchik_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (dtgdRobotGerchik.SelectedIndex >= 0)
            {
                GechikRobotItem grItem = ((DataGrid)sender).SelectedItem as GechikRobotItem;
                AddNewGerchikRobot ngr = new AddNewGerchikRobot(grItem, DataProvider, true);
                ngr.ShowDialog();
            }
        }

        private void DocumentContent_Loaded(object sender, RoutedEventArgs e)
        {
            _dsTimer.Interval = TimeSpan.FromMilliseconds(1000);
            _dsTimer.Start();
            _dsTimer.Tick += new EventHandler(_dsTimer_Tick);
        }


      

        public void _dsTimer_Tick(Object sender, EventArgs args)
        {
            bool running = MainWindow.BConnected;

            btnStart.IsEnabled = running;
            btnStop.IsEnabled = running;

            if (running == true)
            {
                HistoryItems newHistoryItems = new HistoryItems();
                if (DataProvider.GechikRobotItemList.Count > 0)
                {
                    foreach (var item in DataProvider.GechikRobotItemList)
                    {
                        if (!MainWindow.ColInstrumentSubscribe.Contains(item.Instrument) && item.IsRun == true)
                        {
                            if (DataProvider.SecuritiesList.Count > 0)
                                foreach (var item2 in DataProvider.SecuritiesList)
                                {
                                    if (item2.Seccode == item.Instrument)
                                    {
                                        string res = MainWindow.OConn.SendCommand(DataProvider.TransaqCommand.SubscribeQuotations(item2.Secid));
                                        MainWindow.ColInstrumentSubscribe.Add(item.Instrument);
                                        MainWindow.WriteLog("ServerReply: " + res);
                                        List<int> list = new List<int>();
                                        list.Add(item2.Secid);
                                        res = MainWindow.OConn.SendCommand(DataProvider.TransaqCommand.SubscribeTick(list));
                                        MainWindow.WriteLog("ServerReply: " + res);
                                    }
                                }

                        }

                        //Получение данных по истори
                        if (MainWindow.DictionaryHistoryData.Where(a => a.Seccode == item.Instrument).
                            Where(a => a.TimeFrame == MainWindow.DictionaryTimeFrame.FirstOrDefault(x => x.Value == item.TimeFrame).Key).ToList().Count == 0

                            && item.IsRun == true)
                        {
                            if (DataProvider.SecuritiesList.Count > 0)
                                foreach (var item2 in DataProvider.SecuritiesList)
                                {

                                    if (item2.Seccode == item.Instrument)
                                    {
                                        if (!MainWindow.TicksListInstruments.Contains(item2.Secid))
                                        {
                                            MainWindow.TicksListInstruments.Add(item2.Secid);
                                            string result = MainWindow.OConn.SendCommand(DataProvider.TransaqCommand.SubscribeTick(MainWindow.TicksListInstruments));
                                            MainWindow.WriteLog("ServerReply: " + result);
                                        }

                                        string res = MainWindow.OConn.SendCommand(DataProvider.TransaqCommand.GetHistoryDateBoardSeccode
                                            (item2.Board, item.Instrument, MainWindow.DictionaryTimeFrame.FirstOrDefault(x => x.Value == item.TimeFrame).Key, 100, "true"));
                                        MainWindow.WriteLog("ServerReply: " + res);
                                        MainWindow.DictionaryHistoryData.Add(new HistoryItems() { Seccode = item.Instrument, TimeFrame = MainWindow.DictionaryTimeFrame.FirstOrDefault(x => x.Value == item.TimeFrame).Key });
                                        MainWindow.WriteLog("ServerReply: " + res);
                                    }
                                }

                        }

                    }
                }


                if (DataProvider.GechikRobotItemList.Count > 0)
                {
                    foreach (var item in DataProvider.GechikRobotItemList)
                    {
                       
                        if (item.IsRun == true)
                        {
                            LogikGerchikRobot logik = new LogikGerchikRobot(DataProvider);
                            logik.Start(item);
                        }
                    }

                }
            }
        }
    }
}
